import java.lang.reflect.Array;
import java.util.Arrays;

public class Heap {
    public int[] elem;

    public int useSize;
    public Heap() {
        this.elem = new int[10];
    }

    public void InitHeap(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            useSize++;
        }
    }

    public void createBigHeap() {
        for (int pare = (useSize - 1 - 1)/ 2 ; pare >= 0 ; pare--) {
            shftDown(pare,useSize);
        }
    }
    private void shftDown(int p,int end) {
        int child = 2*p+1;
        while(child < end) {
            if(child + 1 < useSize && elem[child] < elem[child + 1]) {
                child++;
            }
            // swap
            if(elem[p] < elem[child]) {
                swap(p,child);
                p = child;
                child = 2*p+1;
            } else {
                break;
            }
        }

    }
    private void swap(int p, int q ) {
        int tmp = elem[p];
        elem[p] = elem[q];
        elem[q] = tmp;
    }

    public int poll() {
        int tmp = elem[0];
        swap(0,useSize-1);
        useSize--;
        shftDown(0,useSize);
        return tmp;

    }

    public void offer(int val) {
        if(isfull()) {
            elem = Arrays.copyOf(elem,elem.length*2);
        }
        elem[useSize] = val;
        useSize++;
        siftUp(useSize-1);


    }
    public void siftUp(int child) {
        int p = (child - 1) / 2;
        while( child > 0) {
            if(elem[p] < elem[child] ) {
                swap(p,child);
                child = p;
                p = (child - 1) /2 ;

            } else {
                break;
            }
        }

    }
    public  boolean isfull() {
        return useSize == elem.length;
    }

}
